package com.xiaoshuidi.cloud.module.member.xxljob;


import cn.hutool.core.util.ObjectUtil;
import com.xiaoshuidi.cloud.framework.common.exception.ServiceException;
import com.xiaoshuidi.cloud.framework.common.exception.enums.GlobalErrorCodeConstants;
import com.xiaoshuidi.cloud.framework.common.util.json.JsonUtils;
import com.xiaoshuidi.cloud.framework.tenant.core.aop.TenantIgnore;
import com.xiaoshuidi.cloud.framework.tenant.core.context.TenantContextHolder;
import com.xiaoshuidi.cloud.module.contract.api.ContractApi;
import com.xiaoshuidi.cloud.module.contract.vo.ContractRoomReqVO;
import com.xiaoshuidi.cloud.module.member.enums.point.PointRecordEnums;
import com.xiaoshuidi.cloud.module.member.pojo.point.MemberPointsRecordEntity;
import com.xiaoshuidi.cloud.module.member.pojo.user.MemberUser;
import com.xiaoshuidi.cloud.module.member.service.point.MemberPointsRecordService;
import com.xiaoshuidi.cloud.module.member.service.point.MemberPointsService;
import com.xiaoshuidi.cloud.module.member.service.user.MemberUserService;
import com.xiaoshuidi.cloud.module.member.xxljob.param.CompensationBirthdayPointsParamVO;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * 补发生日积分
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class CompensationBirthdayPointsJob {
    private final MemberUserService memberUserService;
    private final MemberPointsService memberPointsService;
    private final MemberPointsRecordService memberPointsRecordService;
    private final ContractApi contractApi;

    /**
     * 补偿生日积分
     */
    @TenantIgnore
    @XxlJob("compensation-birthday-points")
    @Transactional(rollbackFor = Exception.class)
    public void CompensationBirthdayPoints() {
        String jobParam = XxlJobHelper.getJobParam();
        // 查询生日在8月份的用户
        log.info("[补偿生日积分] -- 开始,参数:{}", jobParam);
        // 参数校验
        if (ObjectUtil.isEmpty(jobParam)) {
            String string = JsonUtils.toJsonString(new CompensationBirthdayPointsParamVO().setApartmentIds(new ArrayList<>()));
            throw new ServiceException(GlobalErrorCodeConstants.BAD_REQUEST.getCode(), "请填写参数，格式：" + string);
        }
        CompensationBirthdayPointsParamVO paramVO = JsonUtils.parseObject(jobParam, CompensationBirthdayPointsParamVO.class);
        if (ObjectUtil.isEmpty(paramVO.getMonth())) {
            throw new ServiceException(GlobalErrorCodeConstants.BAD_REQUEST.getCode(), "请填写月份");
        }
        // 月份
        Integer month = paramVO.getMonth();
        List<Long> apartmentIds = paramVO.getApartmentIds();
        List<MemberUser> memberUserList = memberUserService.getUserByBirthdayMonth(month.toString());
        // 计算当月开始时间和结束时间
        LocalDateTime start = LocalDateTime.of(LocalDateTime.now().getYear(), month, 1, 0, 0, 0);
        LocalDateTime end = LocalDateTime.of(LocalDateTime.now().getYear(), month, start.with(TemporalAdjusters.lastDayOfMonth()).getDayOfMonth(), 23, 59, 59);
        log.info("[补偿生日积分] -- 时间段:{} ~ {}", start, end);

        // 获取8月份已发送生日积分的用户
        List<MemberPointsRecordEntity> recordEntities = memberPointsRecordService.getBirthdayRecordByCreateTime(start, end);
        List<Long> ids = recordEntities.stream().map(MemberPointsRecordEntity::getTenantUserId).collect(Collectors.toList());

        // 过滤掉已发放生日积分的用户
        memberUserList = memberUserList.stream().filter(memberUser -> {
            if (ids.contains(memberUser.getId())) {
                return false;
            } else {
                return true;
            }
        }).collect(Collectors.toList());

        memberUserList.forEach(memberUser -> {
            // 租客的合同列表
            TenantContextHolder.setTenantId(memberUser.getTenantId());
            // 当前已入住的合同
            List<ContractRoomReqVO> contractRoomReqVOS = contractApi.getContractByMemberId(memberUser.getId()).getCheckedData();
            // 如果当前是入住中的，补发积分
            // Long apartmentId = null;
            if(ObjectUtil.isNotEmpty(contractRoomReqVOS)){
                List<Long> apartments = contractRoomReqVOS.stream().map(ContractRoomReqVO::getApartmentId).distinct().collect(Collectors.toList());
                for (Long apartment : apartments) {
                    if(ObjectUtil.isEmpty(apartmentIds) || apartmentIds.contains(apartment)){
                        memberPointsService.memberPointsChange(memberUser.getId(), 2000, PointRecordEnums.BIRTHDAY_GIFT, "补发23年8月份在租租客生日2000积分");
                        log.info("补发23年8月份租客{}生日2000积分", JsonUtils.toJsonString(memberUser));
                        break;
                    }
                }
            }
/*            Boolean flag = false;
            // 生日当天是否在租
            for (ContractRoomReqVO contractRoomReqVO : contractRoomReqVOS) {
                LocalDate startTime = contractRoomReqVO.getStartTime();
                LocalDate actualEndTime = contractRoomReqVO.getActualEndTime();
                LocalDate birthday = memberUser.getBirthday();
                flag = (birthday.isAfter(startTime) && birthday.isBefore(actualEndTime)) || birthday.equals(startTime) || birthday.equals(actualEndTime);
                // 如果生日当天存在一份合同,则赠送积分
                if (flag) {
                    apartmentId = contractRoomReqVO.getApartmentId();
                    break;
                }
            }

            if (flag) {
                // 检查门店
                if ((ObjectUtil.isNotEmpty(apartmentIds) && apartmentIds.contains(apartmentId)) || (ObjectUtil.isEmpty(apartmentIds))) {
                    memberPointsService.memberPointsChange(memberUser.getId(), 2000, PointRecordEnums.BIRTHDAY_GIFT, "补发23年8月份在租租客生日2000积分");
                    log.info("补发23年8月份租客{}生日2000积分", JsonUtils.toJsonString(memberUser));
                }
            }*/
            TenantContextHolder.clear();
        });
        log.info("[补偿8月份未发放的生日积分] -- 完成");
    }
}
